package com.ruoyi.common.core.utils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class Helper {

    /**
     * 生成 num 数量的字母+数字随机字符
     * @param num
     * @return
     */
    public static String generateRandomCharacter(Integer num) {
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < num; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }

        return sb.toString();
    }



    /**
     * MD5加密
     *
     * @param str 需要加密的内容
     * @return 加密后的数据
     */
    public static String getMd5(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] bs = md5.digest(str.getBytes());
        StringBuilder sb = new StringBuilder(40);
        for (byte x : bs) {
            if ((x & 0xff) >> 4 == 0) {
                sb.append("0").append(Integer.toHexString(x & 0xff));
            } else {
                sb.append(Integer.toHexString(x & 0xff));
            }
        }
        return sb.toString();
    }

    /**
     * 获取unix时间戳
     *
     * @return 时间转换为s的数据
     */
    public static Long getUnixTime(String dateStr) {
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long epoch = df.parse(dateStr).getTime();
            return epoch / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    /**
     * 逗号隔开的字符串转换为int列表
     * @param str
     * @return
     */
    public static List<Integer> strToIntegerList(String str,String regex){
        List<Integer> intList = new ArrayList<>();
        if(str != null){
            List<String> strList =  Arrays.asList(str.split(regex));
            intList = strList.stream().map(Integer::parseInt).collect(Collectors.toList()); // 转换为int数组
        }
        return intList.isEmpty() ? null : intList;
    }

    /**
     * 获取时间戳 秒
     * @param localDateTime
     * @return
     */
    public static Long getTimeStampByLocalDate(LocalDateTime localDateTime){
        return localDateTime.toEpochSecond(ZoneOffset.of("+8"));
    }

    public static String getDateFormat(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 调用format()方法进行日期格式化并打印结果
        return sdf.format(date);
    }

    public static String formatTencentTime(String time,Integer type){
        try {
            String formatStr;
            if(type == 0){
                formatStr = "yyyy-MM-dd'T'HH:mm:ss'Z'";
            }else {
                formatStr = "yyyy-MM-dd'T'HH:mm:ss+08:00";
            }
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            if(type == 0){
                format.setTimeZone(TimeZone.getTimeZone("UTC"));
            }

            return getDateFormat(format.parse(time));
        } catch (ParseException e) {
            return null;
        }
    }

    public static Long getCurrentTimeStamp(){
        return System.currentTimeMillis() / 1000;
    }

    public static Integer getLiveDelayTime(Integer delay) {
        return delay == 0 ? 0 : delay == 1 ? 4 : 8;
    }

    public static List<String> strToStrList(String str, String regex) {
        List<String> strList = new ArrayList<>();
        if(str != null){
            strList = Arrays.asList(str.split(regex));
        }
        return strList.isEmpty() ? null : strList;
    }

    public static LocalDate getLocalDate(String date,String format){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return LocalDate.parse(date,formatter);
    }

    public static LocalDateTime getLocalDateTime(String date,String format){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(date,formatter);
    }

    public static String getFormatLocalDateTime(LocalDateTime dateTime,String format){
        return dateTime.format(DateTimeFormatter.ofPattern(format));
    }

    public static String getUTCTime(LocalDateTime dateTime) {
        ZonedDateTime zonedDateTime = ZonedDateTime.of(dateTime, ZoneId.systemDefault());
        ZonedDateTime utcDateTime = zonedDateTime.withZoneSameInstant(ZoneId.of("UTC"));
        return utcDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"));
    }

    /**
     * 根据时间戳(秒)转换为LocalDateTime
     * @param timestamp
     * @return
     */
    public static LocalDateTime getTimeByTimestamp(Long timestamp){
        Instant instant = Instant.ofEpochMilli(timestamp * 1000);
        return LocalDateTime.ofInstant(instant, ZoneId.of("UTC+8"));
    }

    public static String flowConvert(BigDecimal liveFlowBalance) {
        String liveBalanceStr = liveFlowBalance + "M";
        if(liveFlowBalance.doubleValue() > 1024){
            // 大于1024M 单位转换为G
            BigDecimal resultBalance = liveFlowBalance.divide(BigDecimal.valueOf(1024),2, RoundingMode.HALF_UP);
            String unit = "G";
            if(resultBalance.doubleValue()> 1024){
                // 单位再转换为T
                resultBalance = resultBalance.divide(BigDecimal.valueOf(1024),2,RoundingMode.HALF_UP);
                unit = "T";
            }
            liveBalanceStr = resultBalance + unit;
        }
        return liveBalanceStr;
    }

    /**
     * 时间转换器 转换为 时分秒的格式
     * @param seconds
     * @return
     */
    public static String timeConverter(Integer seconds){
        int hours = seconds / 3600; // 计算小时部分
        int minutes = (seconds % 3600) / 60; // 计算分钟部分
        int remainingSeconds = seconds % 60; // 计算余下的秒数

        String resultStr = remainingSeconds + "秒";

        if(hours > 0){
            resultStr = hours + "小时";
            if(minutes > 0){
                resultStr = resultStr + String.format("%02d", minutes) + "分钟";
            }
            if(remainingSeconds > 0){
                resultStr = resultStr + String.format("%02d", remainingSeconds) + "秒";
            }
        }else if(minutes > 0){
            resultStr = minutes + "分钟";
            if(remainingSeconds > 0){
                resultStr = resultStr + String.format("%02d", remainingSeconds) + "秒";
            }
        }
        return resultStr;
    }

    public static void main(String[] args) {
        String s = generateRandomCharacter(111);
        System.out.println(s);
    }


    /**
     * 获取分辨率类型
     * @param widthStr
     * @param heightStr
     * @return
     */
    public static Integer getResolutionRatioType(String widthStr, String heightStr) {
        int width = Integer.parseInt(widthStr);
        int height = Integer.parseInt(heightStr);

        int longSize = Math.max(width, height); // 长边
        int shortSize = Math.min(width, height); // 短边

        if(longSize <= 640 && shortSize <= 480){
            return 0;
        }else if (longSize <= 1280 && shortSize <= 720){
            return 1;
        }else if (longSize <= 1936 && shortSize <= 1088){
            return 2;
        }else if(longSize <= 2560 && shortSize <= 1440){
            return 3;
        }else {
            return 4;
        }
    }


    /**
     * 根据URL地址获取文件
     * 得到file对象
     * @param path URL网络地址
     * @return File
     */
    public static File getFileByHttpURL(String path){
        String newUrl = path.split("[?]")[0];
        String[] suffix = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = suffix[suffix.length - 1];
        File file = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            file = File.createTempFile("report",fileName);//创建临时文件
            URL urlFile = new URL(newUrl);
            inputStream = urlFile.openStream();
            outputStream = Files.newOutputStream(file.toPath());

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 分钟转换为小时
     * @param timeOn
     * @return
     */
    public static String secondToHour(Integer timeOn) {
        Integer hour = timeOn / 60;
        Integer second = timeOn % 60;
        return String.format("%02d",hour) + ":" + String.format("%02d",second);
    }
}
